<template>
  <PageLayout full :page-style="pageStyle">
    <!--头部导航-->
    <template #header>
      <HeaderLayout show-back>
        <view>通用设置</view>
      </HeaderLayout>
    </template>
    <!--内容-->
    <view class="container">
      <!--谷电时间设置-->
      <view class="cell border-short">
        <view class="set-text">谷电时间</view>
        <switch
          class="switch-style"
          color="var(--primary-color)"
          :checked="valleySwitch"
          style="transform: scale(0.8)"
          @change="valleySwitchChange"
        />
      </view>
      <!--分割线-->
      <view class="cell border" @click="setElec" v-if="valleySwitch">
        <view class="set-text">启用时间</view>
        <view class="right-cell">
          <view class="right-text"
            >{{ valleyStartTime }}-{{ isTomorrowData_valley ? '次日' : '' }}{{ valleyEndTime }}</view
          >
          <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
        </view>
      </view>
      <!--消息推送免打扰设置-->
      <view class="cell message border-short">
        <view class="set-text">消息推送免打扰设置</view>
        <switch
          class="switch-style"
          color="var(--primary-color)"
          :checked="messageSwitch"
          style="transform: scale(0.8)"
          @change="messageSwitchChange"
        />
      </view>
      <!--分割线-->
      <!--启用时间-->
      <view class="cell border" @click="setMessage" v-if="messageSwitch">
        <view class="set-text">启用时间</view>
        <view class="right-cell">
          <view class="right-text"
            >{{ valleyMessageStartTime }}-{{ isTomorrowData_message ? '次日' : '' }}{{ valleyMessageEndTime }}</view
          >
          <image class="arrow-right" :src="'/static/ic_right_arrow.png'"></image>
        </view>
      </view>
    </view>
  </PageLayout>
  <!--谷电时间设置-->
  <Drawer v-model:show="elecSetting" :title="$t('GeneralSetting.PowerDowntimeSetting.Text')">
    <view class="popunp-tips">{{ $t('GeneralSetting.SetPowerDowntimeDrawer.Text') }}</view>
    <ElecPeak
      :show="elecSetting"
      :start-time="valleyStareTimeList"
      :end-time="valleyEndTimeList"
      :cur-start-time="curValleyStartTime"
      :cur-end-time="curValleyEndTime"
      @timechange="onElecTimeChange"
      @isPicking="onIsPicking"
      :is-tomorrow="isTomorrow"
    />
    <template #footer>
      <view class="activation-time-btn display-around">
        <view class="time-btn cancel--btn" @click="cancelPeak">{{ $t('APP.Common.Cancel.Text') }}</view>
        <view class="time-btn save-btn" @click="confirmPeak">{{ $t('APP.Common.Confirm.Text') }}</view>
      </view>
    </template>
  </Drawer>
  <!--免打扰时间设置-->
  <Drawer v-model:show="messageSetting" title="消息推送免打扰设置" class="message-drawer">
    <view class="popunp-tips">{{ $t('GeneralSetting.SetDonotDisturbDrawer.Text') }}</view>
    <MessagePeak
      :show="messageSetting"
      :start-time-hour="valleyMessageStartTimeList"
      :start-time-min="valleyMessageEndTimeList"
      :end-time-hour="valleyMessageStartTimeList"
      :end-time-min="valleyMessageEndTimeList"
      :cur-start-hour="curMessageStartHour"
      :cur-start-min="curMessageStartMinute"
      :cur-end-hour="curMessageEndHour"
      :cur-end-minute="curMessageEndMinute"
      @timechange="messageChange"
      :is-tomorrow="isTomorrow_message"
      @isPicking="onIsPicking"
    ></MessagePeak>
    <template #footer>
      <view class="activation-time-btn display-around">
        <view class="time-btn cancel--btn" @click="cancelMessageSetting">{{ $t('APP.Common.Cancel.Text') }}</view>
        <view class="time-btn save-btn" @click="confirmMessageSetting">{{ $t('APP.Common.Confirm.Text') }}</view>
      </view>
    </template>
  </Drawer>
</template>
<script setup lang="ts">
import PageLayout from '@/layout/page/page.vue'
import HeaderLayout from '@/layout/page/header.vue'
import Drawer from '@/common/drawer.vue'
import ElecPeak from '@/common/elecPeak.vue'
import MessagePeak from '@/common/messagePeak.vue'
import { useAccountStore } from '@/store/account'
import { onLoad } from '@dcloudio/uni-app'
import { useI18n } from 'vue-i18n'
import {
  getPersonalPreference as getPersonalPreferenceAPI,
  saveVallertPersonalPreference as saveVallertPersonalPreferenceAPI,
  saveMessagePersonalPreference as saveMessagePersonalPreferenceAPI,
} from '@/api/generalSetting'
import { actionDebounce, showLoading } from '@/utils/mpHelper'
import { trackEvent, TrackType } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { cloneDeepWith, noConflict, stubArray } from 'lodash'

const accountStore = useAccountStore()
const i18n = useI18n()

const valleyStartTime = ref('')
const valleyEndTime = ref('')
const valleyMessageStartTime = ref('23:00')
const valleyMessageEndTime = ref('07:00')
const elecSetting = ref(false)
const messageSetting = ref(false)
const messageSwitch = ref(false)
const valleySwitch = ref(false)

const pageStyle = {
  backgroundColor: '#F4F4F4',
}
let isPicking = false
let elecStart = ''
let elecEnd = ''
let messageStart = ''
let messageEnd = ''

const isTomorrow = ref(true)
const isTomorrowData_valley = ref(true)
const isTomorrow_message = ref(true)
const isTomorrowData_message = ref(true)
const curValleyStartTime = computed(() => accountStore.valleyElecStartTime)
const curValleyEndTime = computed(() => accountStore.valleyElecEndTime)

/**
 * 初始化谷电时间数据
 */
const valleyStareTimeList = ref<string[]>([])
let valleyEndTimeList = ref<string[]>([])

// 消息免打扰初始值
let startHourMax = 23
let startHourMin = 21

const valleyMessageStartTimeList = ref<string[]>([])
const valleyMessageEndTimeList = ref<string[]>([])
for (var i = startHourMin; i <= startHourMax; i++) {
  for (var j = 0; j <= 23; j++) {
    let tempMinute = j < 10 ? '0' : ''
    valleyMessageStartTimeList.value.push(`${tempMinute}${j}`)
    // 增加24:00
    if (i === startHourMax && j === 24) {
      valleyMessageStartTimeList.value.push('00')
    }
  }
}

for (var y = 0; y <= 59; y++) {
  let tempMinute = y < 10 ? '0' + y.toString() : y.toString()
  valleyMessageEndTimeList.value.push(tempMinute)
}

onLoad(() => {
  // 初始化谷电时间数据
  initValleyTimeData()
  //获取通用设置数据
  getPersonalPreference()
})

/**
 * 谷电时间动态处理是否是次日
 */
function dynamicRefreshTimeData(elecStart: string, elecEnd: string) {
  isTomorrow.value = compareStartAndEndTime(elecStart, elecEnd)
}

/**
 * 免打扰动态处理是否是次日
 */
function dynamicRefreshMessageTimeData(elecStart: string, elecEnd: string) {
  isTomorrow_message.value = compareStartAndEndTime(elecStart, elecEnd)
}
/**
 * 比较起始和结束时间
 */
function compareStartAndEndTime(elecStart: string, elecEnd: string) {
  let elecStart_temp = elecStart.replace(':', '')
  let elecEnd_temp = elecEnd.replace(':', '')
  let resultFlag = parseInt(elecStart_temp) - parseInt(elecEnd_temp)
  return resultFlag > 0
}
/**
 * 修改消息时间
 */
function messageChange(start: string, end: string) {
  messageStart = start
  messageEnd = end
  dynamicRefreshMessageTimeData(start, end)
}
/**
 * 初始化谷电时间数据
 */

function initValleyTimeData() {
  const minutes = ['00', '30']
  let hours = []
  for (var i = 0; i < 24; i++) {
    var hourString = i.toString()
    if (i < 10) {
      hourString = '0' + hourString
    }
    hours.push(hourString)
    for (var j = 0; j < 2; j++) {
      valleyStareTimeList.value.push(hourString + ':' + minutes[j % 2])
    }
  }
  valleyEndTimeList = cloneDeepWith(valleyStareTimeList)
}
/**
 * 消息免打扰起始时间小时和分钟
 */
const curMessageStartHour = computed(() => {
  let startHour = valleyMessageStartTime.value.split(':')[0]
  return startHour
})

const curMessageStartMinute = computed(() => {
  let startMinute = valleyMessageStartTime.value.split(':')[1]
  return startMinute
})

const curMessageEndHour = computed(() => {
  let startMinute = valleyMessageEndTime.value.split(':')[0]
  return startMinute
})

const curMessageEndMinute = computed(() => {
  let startMinute = valleyMessageEndTime.value.split(':')[1]
  return startMinute
})
/**
 * 获取通用设置数据数据
 */
async function getPersonalPreference() {
  showLoading(async () => {
    const res = await getPersonalPreferenceAPI()
    if (res.code === 0) {
      messageSwitch.value = res.data.muteNotification.enabled === 1
      valleySwitch.value = res.data.valleyTime.enabled === 1
      // 谷电时间
      if (valleySwitch.value === true) {
        valleyStartTime.value = res.data.valleyTime.startTime
        valleyEndTime.value = res.data.valleyTime.endTime
        elecStart = valleyStartTime.value
        elecEnd = valleyEndTime.value
        accountStore.undateElecTime(res.data.valleyTime.startTime, res.data.valleyTime.endTime, true)
        dynamicRefreshTimeData(elecStart, elecEnd)
        isTomorrowData_valley.value = compareStartAndEndTime(elecStart, elecEnd)
      }
      accountStore.isSetValleyTime = valleySwitch.value
      // 免打扰
      if (messageSwitch.value === true) {
        valleyMessageStartTime.value = res.data.muteNotification.startTime
        valleyMessageEndTime.value = res.data.muteNotification.endTime
        messageStart = valleyMessageStartTime.value
        messageEnd = valleyMessageEndTime.value
        accountStore.updateMessageTime(res.data.muteNotification.startTime, res.data.muteNotification.endTime)
        isTomorrowData_message.value = compareStartAndEndTime(messageStart, messageEnd)
      }
    } else {
      console.error('请求通用设置失败' + JSON.stringify(res.data))
    }
  })
}

/**
 * 显示谷电时间弹窗
 */
function setElec() {
  elecSetting.value = true
}
/**
 * 显示免打扰时间弹窗
 */
function setMessage() {
  messageSetting.value = true
}
/**
 * 设置谷电时间
 */
const confirmPeak = actionDebounce({
  delay: 300,
  call: async () => {
    if (isPicking) {
      return uni.showToast({
        title: i18n.t('APP.Common.OperationFastWaitTips.Text'),
        mask: true,
        icon: 'none',
      })
    }

    if (!startEqualToEndTip(elecStart, elecEnd)) {
      return
    }
    let res: any = await saveVallertPersonalPreferenceAPI(1, elecStart, elecEnd)
    elecSetting.value = false

    if (res.code === 0) {
      isTomorrowData_valley.value = compareStartAndEndTime(elecStart, elecEnd)
      uni.showToast({
        title: i18n.t('APP.Common.SetSucess.Text'),
        icon: 'success',
        duration: 2000,
      })
    }
    valleyStartTime.value = elecStart
    valleyEndTime.value = elecEnd
    accountStore.undateElecTime(elecStart, elecEnd, true)
    safeTrack(() => {
      trackEvent(
        'set_valley_power',
        {
          switch_on: true,
          timerange: `${valleyStartTime.value}-次日${valleyEndTime.value}`,
          successOrNot: res.code == 0,
          error_code: res.code,
          response_msg: res.msg,
        },
        TrackType.ApplianceDetail,
        'My.GeneralSetting.Valley.Dialog.Sure'
      )
    })
  },
  catch: (e) => {
    elecSetting.value = false
    uni.showToast({
      title: i18n.t('APP.Common.SetFail.Text'),
      icon: 'error',
      duration: 2000,
    })
    safeTrack(() => {
      trackEvent(
        'set_valley_power',
        {
          switch_on: true,
          timerange: `${valleyStartTime.value}-次日${valleyEndTime.value}`,
          successOrNot: e.code == 0,
          error_code: e.code,
          response_msg: e.msg,
        },
        TrackType.ApplianceDetail,
        'My.GeneralSetting.Valley.Dialog.Sure'
      )
    })
  },
})
/**
 * 取消谷电弹窗设置
 */
function cancelPeak() {
  elecSetting.value = false
}
/**
 * 改变谷电时间
 * @param start 开始时间
 * @param end 结束时间
 */
function onElecTimeChange(start: string, end: string) {
  elecStart = start
  elecEnd = end
  dynamicRefreshTimeData(elecStart, elecEnd)
}

/**
 * 谷电时间选择器是否正在滚动
 * @param value
 */
function onIsPicking(value: boolean) {
  isPicking = value
}
/**
 * 确定修改消息免打扰
 */
const confirmMessageSetting = actionDebounce({
  delay: 300,
  call: async () => {
    if (isPicking) {
      return uni.showToast({
        title: i18n.t('APP.Common.OperationFastWaitTips.Text'),
        mask: true,
        icon: 'none',
      })
    }
    if (!startEqualToEndTip(messageStart, messageEnd)) {
      return
    }
    messageSetting.value = false
    let res = await saveMessagePersonalPreferenceAPI(1, messageStart, messageEnd)
    if (res.code === 0) {
      isTomorrowData_message.value = compareStartAndEndTime(messageStart, messageEnd)
      uni.showToast({
        title: i18n.t('APP.Common.SetSucess.Text'),
        icon: 'success',
        duration: 2000,
      })
      safeTrack(() => {
        trackEvent(
          'set_mute_notification',
          {
            switch_on: true,
            timerange: `${valleyMessageStartTime.value}-次日${valleyMessageEndTime.value}`,
            successOrNot: res.code == 0,
            error_code: res.code,
            response_msg: res.msg,
          },
          TrackType.BusinesssScene,
          'My.GeneralSetting.Mute.Dialog.Sure'
        )
      })
    }
  },
  then: () => {
    valleyMessageStartTime.value = messageStart
    valleyMessageEndTime.value = messageEnd
    accountStore.updateMessageTime(messageStart, messageEnd)
  },
  catch: (e) => {
    messageSetting.value = false
    uni.showToast({
      title: i18n.t('APP.Common.SetFail.Text'),
      icon: 'error',
      duration: 2000,
    })
    safeTrack(() => {
      trackEvent(
        'set_mute_notification',
        {
          switch_on: true,
          timerange: `${valleyMessageStartTime.value}-次日${valleyMessageEndTime.value}`,
          successOrNot: false,
          error_code: e.code,
          response_msg: e.msg,
        },
        TrackType.BusinesssScene,
        'My.GeneralSetting.Mute.Dialog.Sure'
      )
    })
  },
})

/**
 * 起始时间和结束时间相等时的提示
 */
function startEqualToEndTip(startTime: string, endTime: string) {
  if (startTime === endTime) {
    uni.showToast({
      title: i18n.t('GeneralSetting.GlobaleSettingTitle.ErrorTip.Text'),
      icon: 'none',
      duration: 2000,
    })
    return false
  } else {
    return true
  }
}

/**
 * 取消修改消息免打扰
 */
function cancelMessageSetting() {
  messageSetting.value = false
}

/**
 *
 * @param e 谷电时间开关
 */
async function valleySwitchChange(e: any) {
  let res: any = null
  showLoading(async () => {
    if (e.detail.value === true) {
      res = await saveVallertPersonalPreferenceAPI(1, '21:00', '07:00')
    } else {
      res = await saveVallertPersonalPreferenceAPI(0, '21:00', '07:00')
      isTomorrowData_valley.value = true
    }
    if (res.code != 0) {
      valleySwitch.value = !e.detail.value
    } else {
      valleySwitch.value = e.detail.value
      valleyStartTime.value = '21:00'
      valleyEndTime.value = '07:00'
      accountStore.undateElecTime('21:00', '07:00', true)
      accountStore.isSetValleyTime = valleySwitch.value
    }

    // console.error(valleyStartTime.value, valleyEndTime.value)
    safeTrack(() => {
      trackEvent(
        'set_valley_power',
        {
          switch_on: e.detail.value,
          timerange: `${valleyStartTime.value}-次日${valleyEndTime.value}`,
          successOrNot: res.code == 0,
          error_code: res.code,
          response_msg: res.msg,
        },
        TrackType.ApplianceDetail,
        'My.GeneralSetting.Valley.Switch'
      )
    })
  })
}

/**
 * 消息免打扰设置开关
 */
async function messageSwitchChange(e: any) {
  let res
  showLoading(async () => {
    if (e.detail.value === true) {
      res = await saveMessagePersonalPreferenceAPI(1, '23:00', '07:00')
    } else {
      res = await saveMessagePersonalPreferenceAPI(0, '23:00', '07:00')
    }
    if (res.code != 0) {
      messageSwitch.value = !e.detail.value
    } else {
      messageSwitch.value = e.detail.value
      valleyMessageStartTime.value = '23:00'
      valleyMessageEndTime.value = '07:00'
      accountStore.updateMessageTime('23:00', '07:00')
      dynamicRefreshMessageTimeData('23:00', '07:00')
    }
  })
  safeTrack(() => {
    trackEvent(
      'set_mute_notification',
      { switch_on: e.detail.value, timerange: `${valleyMessageStartTime.value}-次日${valleyMessageEndTime.value}` },
      TrackType.BusinesssScene,
      'My.GeneralSetting.Mute.Switch'
    )
  })
}
</script>

<style scoped lang="less">
@import '@/styles/common.less';
.popunp-tips {
  font-size: 28rpx;
  font-weight: 400;
  letter-spacing: -0.30000001192092896px;
  text-align: left;
  display: flex;
  align-items: center;
  opacity: 0.6000000238418579;
  margin-bottom: 64rpx;
}

// 设置
.container {
  background-color: #f4f4f4;
  margin: 16rpx 0rpx;

  .cell {
    background-color: #fff;
    padding: 0 32rpx;
    height: 88rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
  }
  .border {
    border-bottom: 1rpx solid rgba(233, 233, 237, 1);
  }
  .border-short {
    &::after {
      display: block;
      width: calc(100% - 32rpx);
      height: 1rpx;
      background-color: rgba(233, 233, 237, 1);
      position: absolute;
      bottom: 0;
      content: '';
    }
  }
  .switch-style {
    position: absolute;
    right: 16rpx;
  }
  .message {
    margin-top: 16rpx;
  }
  .user-report-cell {
    background-color: #fff;
    padding: 0 32rpx;
    height: 88rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
  }

  // 分割线
  // .line {
  //   height: 1rpx;
  //   background-color: #e2e2e2;
  //   margin: 0rpx 32rpx;
  // }
  .right-cell {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .right-text {
      color: var(--dark-color);
      opacity: 0.6;
      font-weight: 400;
      font-size: 32rpx;
    }
  }
}
// 箭头
.arrow-right {
  width: 14rpx;
  height: 24rpx;
  padding-left: 24rpx;
}

.set-text {
  font-weight: 500;
  font-size: 32rpx;
  color: #333333;
  opacity: 0.9;
}
</style>
